import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { tap, delay, catchError } from 'rxjs/operators';

interface Login {
  name: string;
  username: string;
  _id: string;
  token: string;
}

const AUTH_TOKEN = 'AUTH_TOKEN';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private loginUrl = '/login';
  private authToken = '';

  redirectUrl: string | null = null;

  public get isLoggedIn() {
    return !!this.getToken();
  }

  constructor(private http: HttpClient) {}

  getToken() {
    const token = this.authToken
      ? this.authToken
      : localStorage.getItem(AUTH_TOKEN);
    return token;
  }

  setToken(token: string) {
    token = 'Bearer ' + token;
    this.authToken = token;
    localStorage.setItem(AUTH_TOKEN, token);
  }

  login(value: { username: string; password: string }) {
    return this.http.post<Login>(this.loginUrl, value).pipe(
      tap((data) => {
        this.setToken(data.token);
      }),
    );
  }

  logout(): void {
    this.setToken(null);
  }
}
